﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NETCore.MailKit.Core;
using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XXX.api.Filter;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.XXXEntities;
using Yonyou.U8.BO;
using ZDEntity;
using static XXX.Models.WDFT.WDFT_SaleOrderJinDu;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace XXX.api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    [TypeFilter(typeof(ApiLoggingFilterFactory))]
    public class U8PositionController : ControllerBase
    { 
        private readonly ILogger<U8PositionController> _logger;
        //private readonly IEmailService _EmailService;
        public U8PositionController(ILogger<U8PositionController> logger)
        {           
            _logger = logger;
            //_EmailService = emailService;
        }

        /// <summary>
        /// 推送货位档案
        /// </summary> 
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]

        public RetModel2 Post(JObject obj)
        {
            string requestBody = DbHelper.GetDbString(obj);
            AS_Position model = JsonConvert.DeserializeObject<AS_Position>(obj.ToString());
           
            try
            {

                #region 接口调用间隔
                string strKey = "U8Inventory" + Md5Encrypt.MD5(requestBody);

                if (CacheHelpCore.GetCacheValue(strKey) == null)
                {
                    CacheHelpCore.SetChacheValue(strKey, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CanShu.chkRepeat);
                }
                else
                {
                    /* return null*/
                    return new RetModel2()
                    {
                        code = 300,
                        message = "接口调用间隔过短"
                    };
                }
                #endregion 接口调用间隔


                // 处理业务逻辑
                string cErr = "";
               
                RetModel2 ret;
                if (model == null)
                {
                    ret = DBService.ReErrObject("入参有误" + cErr);
                }
                else
                {

                    PositionVM vM = new PositionVM();
                    //如果有辅助计量单位，把其他辅助单位全部设置成一样
                   
                    vM.entity =model;
                    //使用默认参数覆盖
                    vM.MergeEntity();
                  
                    //专属导入
                    ret = vM.Import();
                     
                }
            
                              

                return ret;
            }
            catch (Exception ex)
            {
                
                return new RetModel2() { code = 500, message = ex.Message };
            }

        }

         
        /// <summary>
        /// 推送货位档案
        /// </summary>
        /// <param name="cAccount">账套信息，取中间库的信息</param>
        /// <param name="cVouchType">单据类型</param>
        /// <param name="cCode">单据编码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Delete")]
        public RetModel2 Delete(JObject obj)
        {
            string requestBody = DbHelper.GetDbString(obj);
            AS_Position model = JsonConvert.DeserializeObject<AS_Position>(obj.ToString());

            try
            {

                #region 接口调用间隔
                string strKey = "U8Inventory" + Md5Encrypt.MD5(requestBody);

                if (CacheHelpCore.GetCacheValue(strKey) == null)
                {
                    CacheHelpCore.SetChacheValue(strKey, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CanShu.chkRepeat);
                }
                else
                {
                    /* return null*/
                    return new RetModel2()
                    {
                        code = 300,
                        message = "接口调用间隔过短"
                    };
                }
                #endregion 接口调用间隔


                // 处理业务逻辑
                string cErr = "";

                RetModel2 ret;
                if (model == null)
                {
                    ret = DBService.ReErrObject("入参有误" + cErr);
                }
                else
                {

                    PositionVM vM = new PositionVM();
                    vM.entity = model;
                    //使用默认参数覆盖
                    //vM.MergeEntity();
                    //专属导入，根据名称+规格判断是否有料号
                    ret = vM.Delete();

                    //直接生成下个工序单据的出库单
                }
                

                return ret;
            }
            catch (Exception ex)
            {
                 
                return new RetModel2() { code = 500, message = ex.Message };
            }

        }
        /// <summary>
        /// 推送货位档案
        /// </summary>
        /// <param name="cAccount">账套信息，取中间库的信息</param>
        /// <param name="cVouchType">单据类型</param>
        /// <param name="cCode">单据编码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("BatchAdd")]
        public RetModel2 BatchAdd(List<AS_Position> model)
        {
            string requestBody = JsonConvert.SerializeObject(model);
            //List<AS_Inventory> model = JsonConvert.DeserializeObject<List<AS_Inventory>>(requestBody);

            //string requestBody = JsonConvert.SerializeObject(model);
            try
            {

                #region 接口调用间隔
                string strKey = "U8Inventory" + Md5Encrypt.MD5(requestBody);

                if (CacheHelpCore.GetCacheValue(strKey) == null)
                {
                    CacheHelpCore.SetChacheValue(strKey, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CanShu.chkRepeat);
                }
                else
                {
                    /* return null*/
                    return new RetModel2()
                    {
                        code = 300,
                        message = "接口调用间隔过短"
                    };
                }
                #endregion 接口调用间隔


                // 处理业务逻辑
                string cErr = "";

                RetModel2 ret = new RetModel2();
                string cInvcodeList = "";
                string cResult = "";
                int iErrCnt = 0; //失败数量
                if (model == null)
                {
                    ret = DBService.ReErrObject("入参有误" + cErr);
                }
                else
                {
                   List<insertResult> list = new List<insertResult>();
                    PositionVM vM = new PositionVM();
                    foreach (var item in model)
                    {
                       
                        //如果有辅助计量单位，把其他辅助单位全部设置成一样

                        vM.entity = item;
                        //使用默认参数覆盖
                        vM.MergeEntity(); 
                       RetModel2 retnow = vM.Import();

                        insertResult insertResult = new insertResult();
                        insertResult.cReCode = retnow.code.ToString();
                        insertResult.Result = retnow.message;
                        insertResult.cVouCode = item.cPosCode; 
                        if (retnow.code == 200)
                        {
                            //cResult += "ID：" + item.cCurrencyName +"，存货编码：" + retnow.data + "；\r\n";
                            cInvcodeList += item.cPosName + ";";
                        }
                        else
                        {
                            iErrCnt++;
                             //cResult += "名称：" + item.cInvName + "规格:" + item.cInvStd + "生成失败，错误：" + retnow.message + "；\r\n";
                        } 
                        list.Add(insertResult);
                    }
                    if (iErrCnt >= 1 && iErrCnt< model.Count)
                    {
                        ret.code = 300;
                        ret.message = "部分失败" ;
                    }
                    else if ( iErrCnt ==model.Count)
                        {
                            ret.code = 400;
                            ret.message = "全部失败" ;
                        }
                        else
                    {
                        ret.code = 200;
                        ret.message = "全部成功" ;
                    }
                    ret.data = list;
                    //直接生成下个工序单据的出库单
                }
                
            
                return ret;
            }
            catch (Exception ex)
            {
                 return new RetModel2() { code = 500, message = ex.Message };
            }

        }

    }


}
